import puppeteer from 'puppeteer';
import xlsx from 'node-xlsx';
import GoLogin from '../src/gologin.js';
import readline from 'readline';
import fs from 'fs';
import request from 'request';
import { authenticator } from 'otplib';

let GL;
let sheets;
let browser;
let num;
let id;
let excelpath = 'D://谷歌开发者验证号(1).xlsx';
// let excelpath = 'D://谷歌开发者验证号(1).xlsx';

let firstNameIndex = 0;
let lastNameIndex = 1;
let lmailIndex = 2;
let passwordIndex = 3;
let profileNameIndex = 8;
let registSimIndex = 10;
let stepSimIndex = 11;
let developerSimIndex = 12;
let developerNameIndex = 13;
let companyNameIndex = 14;
let cardIndex = 15;

let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2MjhjYTJkNDQ2NDc4ZDZkMzE2Njc0NWUiLCJ0eXBlIjoiZGV2Iiwiand0aWQiOiI2MjhjYTNkYWY3ZjExMTcxMTZjZGRlNDYifQ.dGK_cQSjS1DO1AvK433tpviT6AkpYfd2tjnU4zVKERI';

function proxyInfo(ip, callback) {
  request.get('http://ip-api.com/json/' + ip, {
    json: true,
    headers: {
      Accept: 'application/json',
    },
  }, async (err, res, body) => {
    await callback(ip, body.timezone, body.lat, body.lon, body.countryCode, body.regionName);
  });
}

function newGL(profileId) {
  GL = new GoLogin({
    token: token,
    profile_id: profileId,
    extra_params: ['--start-maximized'],
    uploadCookiesToServer: true,
    tmpdir:'C:\\Users\\Administrator\\AppData\\Local\\Temp\\'

  });
}

(async () => {
  try {
    sheets = xlsx.parse(excelpath);
    const option = process.argv[2].toUpperCase();
    const num = parseInt(process.argv[3]);
    id = process.argv[4];

    // const sheetElement = sheets[2].data[num-1];
    // // const profileId = sheetElement[12];
    // const profileId = sheetElement[12];
    // const key = sheetElement[7];
    // const mail = sheetElement[7];
    // const password = sheetElement[8];

    const sheetElement = sheets[0].data[num-1];
    // const profileId = sheetElement[12];
    const profileId = sheetElement[10];
    const key = sheetElement[11];
    const mail = sheetElement[5];
    const password = sheetElement[6];


    console.log('profileId--' + profileId);
    let proxyCountry = sheetElement[9];
    newGL(profileId);
    let a;
    let data1;
    let pages;
    let length;
    let page;
    let elementHandle;
    let btn;
    let elementHandle1;
    switch (option) {
      case 'START':
        // await newGL();
        GL = new GoLogin({
          token: token,
          profile_id: profileId,
          extra_params: ['--start-maximized'],
          uploadCookiesToServer: true,
          tmpdir:'C:\\Users\\Administrator\\AppData\\Local\\Temp\\'
        });

        a = await GL.start();

        console.log(a.wsUrl);
        data1 = '\n' + id + '|' + a.wsUrl;

        fs.appendFile('file.txt', data1, function (err) {
          if (!err) {
            console.log('wrote data to file.txt');
          } else {
            throw err;
          }
        });

        browser = await puppeteer.connect({
          browserWSEndpoint: a.wsUrl,
          ignoreHTTPSErrors: true,
        });

        pages = await browser.pages();
        length = (await browser.pages()).length;
        page = pages[pages.length - 1];
        await page.goto('https://accounts.google.com/');
        // console.log(await page.$("html"))
        elementHandle = await page.$(
          'input[id="identifierId"]',
        );

        elementHandle.value = '';

        await elementHandle.type(mail, { delay: 1 });

        btn = await (await page.$(
          'div[class="TNTaPb"]',
        )).$('button');
        await btn.click();

        elementHandle1 = await page.$(
          'iframe[title="reCAPTCHA"]',
        );
        await sleep(2000)
        await elementHandle1.click();

        return;
      case 'GMAIL':
        await newGL(profileId);
        getWsUrlById(id, async function (wsurl) {
          browser = await puppeteer.connect({
            browserWSEndpoint: wsurl,
            extra_params: ['--start-maximized'],
            ignoreHTTPSErrors: true,
          });
          let pages = await browser.pages();
          let length = (await browser.pages()).length;
          const page = pages[pages.length - 1];
          await page.goto('https://accounts.google.com/');
          // console.log(await page.$("html"))
          const elementHandle = await page.$(
            'input[id="identifierId"]',
          );

          elementHandle.value = '';

          await elementHandle.type(mail, { delay: 1 });

          let btn = await (await page.$(
            'div[class="TNTaPb"]',
          )).$('button');
          await btn.click();

          await (await page.$(
            'iframe[title="reCAPTCHA"]',
          )).click();
        });
        return;
      case 'PAY':
        await newGL(profileId);
        console.log(option);
        getWsUrlById(id, async function (wsurl) {
          browser = await puppeteer.connect({
            browserWSEndpoint: wsurl,
            ignoreHTTPSErrors: true,
            extra_params: ['--start-maximized'],
          });
          let pages = await browser.pages();
          let length = (await browser.pages()).length;
          const page = pages[pages.length - 1];

          const elementHandle = (await page.$(
            'iframe[title="reCAPTCHA"]',
          )).click();

        });
        return;
      case 'PROFILE':
        await newGL(profileId);
        getWsUrlById(id, async function (wsurl) {
          browser = await puppeteer.connect({
            browserWSEndpoint: wsurl,
            ignoreHTTPSErrors: true,
            extra_params: ['--start-maximized'],
          });
          let pages = await browser.pages();
          let length = (await browser.pages()).length;
          const page = pages[pages.length - 1];

          // console.log(await page.$("html"))
          const elementHandle = await page.$(
            'input[type="password"]',
          );

          elementHandle.value = '';

          await elementHandle.type(password, { delay: 1 });

          let btn = await (await page.$(
            'div[class="TNTaPb"]',
          )).$('button');
          await btn.click();
          await sleep(5000);

          // console.log(await page.$("html"))
          const elementHandle2 = await page.$(
            'input[type="tel"]',
          );

          // elementHandle2.value = '';
          const token = authenticator.generate(key);
          console.log('tk'+token);
          await elementHandle.type(token, { delay: 1 });

          let btn2 = await (await page.$(
            'div[class="TNTaPb"]',
          )).$('button');
          await btn2.click();

          await (await page.$(
            'span[text="Not now"]',
          ));
          // const pagePromise =await browser.newPage();
          // await pagePromise.goto('https://play.google.com/console');
          // const btn3 = await (await pagePromise.$(
          //   'developer-item[debug-id="all-developers"]',
          // ));
          // await btn3.click();
          // let pagePromise =await browser.newPage();
          // await pagePromise.goto('https://play.google.com/console');
          // let btn3 = await (await pagePromise.$(
          //   'developer-item[debug-id="all-developers"]',
          // ));
          // await btn3.click();
        });
        return;
      case 'PAY2':
        await newGL(profileId);
        getWsUrlById(id, async function (wsurl) {
          browser = await puppeteer.connect({
            browserWSEndpoint: wsurl,
            ignoreHTTPSErrors: true,
            extra_params: ['--start-maximized'],
          });
          let pages = await browser.pages();
          let length = (await browser.pages()).length;
          const page = pages[pages.length - 1];

          // console.log(await page.$("html"))
          const elementHandle = await page.$(
            'input[type="tel"]',
          );
          const token = authenticator.generate(key);
          console.log(token);
          elementHandle.value = '';

          await elementHandle.type(token, { delay: 1 });

          let btn = await (await page.$(
            'div[class="TNTaPb"]',
          )).$('button');
          await btn.click();

          // await (await page.$(
          //   'span[text="Not now"]',
          // ));
          // const pagePromise =await browser.newPage();
          // await pagePromise.goto('https://play.google.com/console');
          // const btn3 = await (await pagePromise.$(
          //   'developer-item[debug-id="all-developers"]',
          // ));
          // await btn3.click();
        });
        return;
      case 'STEP':
        await newGL(profileId);
        await GL.setProfileId(profileId);

        getWsUrlById(id, async function (wsurl) {
          browser = await puppeteer.connect({
            browserWSEndpoint: wsurl,
            ignoreHTTPSErrors: true,
            extra_params: ['--start-maximized'],
          });
          let pagePromise =await browser.newPage();
          await pagePromise.goto('https://play.google.com/console');
          let btn = await (await pagePromise.$(
            'developer-item[debug-id="all-developers"]',
          ));
          await btn.click();
          await GL.commitProfile();
          await GL.uploadProfileCookiesToServer();


        });
        return;
      case 'DEVELOPER':
        await newGL();
        getWsUrlById(id, function (wsurl) {

        });
        return;
      case 'UPLOAD':
        await newGL();
        GL.setProfileId(profileId);
        await GL.uploadProfileCookiesToServer();
        // await GL.stopLocal({posting: false});
        return;
    }

  } catch (e) {
    console.log(e);
  }
})();

function getWsUrlById(id, callback) {
  const fRead = fs.createReadStream('file.txt');
  const rl = readline.createInterface({
    input: fRead,
    terminal: false,
  });
  console.log(id);

  rl.on('line', function (line) {
    let strings = line.split('|');

    if (strings[0] === id) {
      console.log(strings[1]);
      rl.on('close', function () {
      });
      callback(strings[1]);
    }
  });
}



function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

